﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Neoseeker.NAMFox.Tests
{
    public class CredentialDecryptor
    {
        private byte[] key;

        public CredentialDecryptor()
        {
        }

        private byte[] Key
        {
            get
            {
                if (this.key != null)
                {
                    return this.key;
                }

                return this.key = Convert.FromBase64String(File.ReadAllText(@"..\..\..\build\NAMFoxTests.key"));
            }
        }

        public string Decrypt(string data)
        {
            byte[] key = this.Key;
            byte[] combinedData = Convert.FromBase64String(data);

            byte[] iv = new byte[16];
            byte[] encryptedData = new byte[combinedData.Length - 16];

            for (int i = 0; i < 16; i++)
            {
                iv[i] = combinedData[i];
            }

            for (int i = 16; i < combinedData.Length; i++)
            {
                encryptedData[i - 16] = combinedData[i];
            }

            RijndaelManaged aes = new RijndaelManaged();

            var decryptor = aes.CreateDecryptor(key, iv);

            var memoryStream = new MemoryStream();
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write);

            cryptoStream.Write(encryptedData, 0, encryptedData.Length);
            cryptoStream.FlushFinalBlock();

            byte[] plainData = memoryStream.ToArray();

            return Encoding.UTF8.GetString(plainData);
        }
    }
}
